import subprocess, time, datetime, re
from hashlib import md5
from oRinPackage import ErrorCollect

class SafeRsync:
	def __init__(self, rTimes, myip=''):
		self.rTimes = rTimes
		self.TaskSign = md5(str(datetime.datetime.now())).hexdigest()
		self.ErrorCollect = ErrorCollect.ErrorCollect()
		self.svrIP = myip
		self.allsvr = {}
		self.ip2id = {}
		self.__IPreg = re.compile('\s*inet ([^ ]+)')
		if not myip: self.svrIP = self.GetMyIP()

	def toRsync(self, rsyncmd):
		for i in range(self.rTimes):
			rsyncDaemon = subprocess.Popen(rsyncmd, shell=True,close_fds=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
			conTMP = rsyncDaemon.communicate()
			rsynCode = rsyncDaemon.returncode
			if rsynCode != 0:
				self.ErrorCollect.push('%s\trsync die \'%s\' %d times.' % (self.svrIP, conTMP[1], i), self.TaskSign)
				time.sleep(10)
				continue
			return False
		else:
			self.ErrorCollect.push('%s: rsync failed.' % self.svrIP, self.TaskSign)
			return True

	def reMD5(self):
		self.TaskSign = md5(str(datetime.datetime.now())).hexdigest()

	def SvrIP(self, modNum):
		return self.ip2id[str(modNum)]

	def GetMyIP(self):
		""" Get all svr ip from output of ifconfig, and return specific ip in gSvr.conf. """
		f = open('/etc/gSvr.conf')
		for line in f:
			ipAdd, number = line.strip().split('\t')
			self.allsvr[ipAdd] = int(number)
			self.ip2id[number] = ipAdd
		f.close()
		mycmd = '/sbin/ifconfig -a'
		rsyncDaemon = subprocess.Popen(mycmd, shell=True,close_fds=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		conTMP = rsyncDaemon.communicate()
		return filter(lambda x: self.allsvr.has_key(x), self.__IPreg.findall(conTMP[0]))[0]

